# _*_ coding: utf-8 _*_
"""
@ 时间    ：2024/10/26 9:26
@ 作者    ：旺财
@ 文件    ：Kmeans算法.py
@ 说明    ：算法原理:随机分配中心点,将距离近似的样本划分为同一类别(中心点的位置会随着迭代不断更新)
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

df = np.array([[3, 2], [4, 1], [3, 6], [4, 7], [3, 9], [6, 8], [6, 6], [7, 7]])

plt.rcParams['font.sans-serif'] = ['SimHei']
_, axs = plt.subplots(1, 3, figsize=(15, 5))

axs[0].scatter(df[:, 0], df[:, 1], c='red', marker='o')
axs[0].set_title('原图')
axs[0].set_xlabel('x')
axs[0].set_ylabel('y')
axs[0].legend(['样本'], loc='lower right')


# 使用KMeans算法将数据分两类
kms = KMeans(n_clusters=2)
kms.fit(df)
label = kms.labels_
print(label)


axs[1].scatter(df[label == 0][:, 0], df[label == 0][:, 1], c='red', marker='o')
axs[1].scatter(df[label == 1][:, 0], df[label == 1][:, 1], c='green', marker='*')
axs[1].set_title('分两类')
axs[1].set_xlabel('x')
axs[1].set_ylabel('y')
axs[1].legend(['类别1', '类别2'], loc='lower right')

# 使用KMeans算法将数据分三类
kms = KMeans(n_clusters=3)
kms.fit(df)
label = kms.labels_
print(label)
# df['label'] = label

axs[2].scatter(df[label == 0][:, 0], df[label == 0][:, 1], c='red', marker='o')
axs[2].scatter(df[label == 1][:, 0], df[label == 1][:, 1], c='green', marker='*')
axs[2].scatter(df[label == 2][:, 0], df[label == 2][:, 1], c='blue', marker='+')
axs[2].set_title('分三类')
axs[2].set_xlabel('x')
axs[2].set_ylabel('y')
axs[2].legend(['类别1', '类别2', '类别3'], loc='lower right')


plt.show()